import XLSX from 'xlsx';
import { batchAudit } from './api';
import { message } from '@/utils/util';
import { strip } from '@/utils';

export default {
  name: 'audit-price-import-modal',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    topChannelList: {
      type: Array,
      default: () => [],
    },
    // taskId: {
    //   type: Array,
    //   default: () => [],
    // },
  },

  data() {
    return {
      formValue: {
        topChannelCode: '',
        list: [],
      },
      stepNumber: 0,
      formRules: {
        goods: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.formValue.list.length === 0) {
                callback('导入信息为空');
              } else {
                callback();
              }
            },
          },
        ],
      },
      formLabelWidth: '300px',
      importing: false,
    };
  },
  watch: {},
  methods: {
    async onSubmit(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          try {
            this.stepNumber = 2;
            this.importing = true;
            let auditGoodses = [];
            console.log('formValue.list', this.formValue.list);
            this.formValue.list.map(item => {
              const { channelCode } = item;
              auditGoodses.push({
                ...item,
                topChannelCode: channelCode.split('_')[0],
              });
            });
            await batchAudit(auditGoodses);
            this.onClose('success');
            this.stepNumber = 3;
            message('提示', '导入成功', 'success');
          } catch (e) {
            message('错误', e.message, 'error');
          }
          this.importing = false;
        }
      });
    },
    onClose(status) {
      this.formValue = {};
      this.$refs.formRef.resetFields();
      this.$refs.upload.clearFiles();
      this.$refs.upload.uploadFiles = [];
      this.$emit('close', status);
      this.stepNumber = 0;
    },
    onChange(file) {
      const reader = new FileReader();
      reader.onload = e => {
        let data = e.target.result;
        const workbook = XLSX.read(data, { type: 'buffer' });
        const [sheetName] = workbook.SheetNames;
        const sheetInfo = workbook.Sheets[sheetName];
        const parsedSheetInfo = XLSX.utils.sheet_to_json(sheetInfo);
        console.log('解析excel得parsedSheetInfo', parsedSheetInfo);
        const result = parsedSheetInfo.map((item, index) => ({
          rowNo: index + 2,
          auditTaskId: String(item['审核任务ID'] || ''),
          id: String(item['审核商品ID'] || ''),
          channelCode: String(item['渠道编码'] || ''),
          newChannelPrice: String(strip(item['建议原价']) || ''),
          newActivityPrice: String(strip(item['建议特价']) || ''),
          auditChannelPrice: String(strip(item['确认原价']) || ''),
          auditActivityPrice: String(strip(item['确认特价']) || ''),
          auditLimitFrequency: String(item['限购频率'] || ''),
          auditLimitNum: String(item['限购数量'] || ''),
          auditActivityPriceLimit: String(item['特价限购'] || ''),
        }));
        console.log('result导入', result);
        this.stepNumber = 1;
        if (result && result.length > 0) {
          const list = [];
          const isNotNext = result.some(item => {
            const {
              rowNo,
              auditTaskId,
              id,
              channelCode,
              newChannelPrice,
              newActivityPrice,
              auditChannelPrice,
              auditActivityPrice,
              auditLimitFrequency,
              auditLimitNum,
              auditActivityPriceLimit,
            } = item;
            const rowText = '第' + rowNo + '行';
            const obj = {};
            if (!auditTaskId) {
              message('提示', rowText + '审核任务ID为空', 'warning');
              return true;
            } else {
              obj.auditTaskId = auditTaskId.trim();
            }
            if (!id) {
              message('提示', rowText + '审核商品ID为空', 'warning');
              return true;
            } else {
              obj.id = id.trim();
            }
            if (
              !(
                newChannelPrice ||
                newActivityPrice ||
                auditChannelPrice ||
                auditActivityPrice ||
                auditLimitFrequency ||
                auditLimitNum ||
                auditActivityPriceLimit
              )
            ) {
              message('提示', rowText + '没有设置调价需求', 'error');
              return true;
            }
            if (!channelCode) {
              message('提示', rowText + '渠道编码为空', 'warning');
              return true;
            } else {
              obj.channelCode = channelCode.trim();
            }
            const reg = /^-?[0-9]\d*$/; // 整数
            const reg2 = /^(0|[1-9][0-9]*)(\.\d{1,5})?$/; // 大于等于0且保留小数点后5位的数字
            if (newChannelPrice && !reg2.test(newChannelPrice)) {
              message('提示', rowText + '建议原价请填写大于等于0且保留小数点后5位的数字', 'warning');
              return true;
            } else {
              obj.newChannelPrice = Number(newChannelPrice);
            }
            if (newActivityPrice && !reg2.test(newActivityPrice)) {
              message('提示', rowText + '建议特价请填写大于等于0且保留小数点后5位的数字', 'warning');
              return true;
            } else {
              obj.newActivityPrice = Number(newActivityPrice);
            }
            if (auditChannelPrice && !reg2.test(auditChannelPrice)) {
              message('提示', rowText + '确认原价请填写大于等于0且保留小数点后5位的数字', 'warning');
              return true;
            } else {
              obj.auditChannelPrice = Number(auditChannelPrice);
            }
            if (auditActivityPrice && !reg2.test(auditActivityPrice)) {
              message('提示', rowText + '确认特价请填写大于等于0且保留小数点后5位的数字', 'warning');
              return true;
            } else {
              obj.auditActivityPrice = Number(auditActivityPrice);
            }
            if (auditLimitFrequency && !reg.test(auditLimitFrequency)) {
              message('提示', rowText + '限购频率请填写整数', 'warning');
              return true;
            } else if (auditLimitFrequency && auditLimitFrequency < -1) {
              message('提示', rowText + '限购频率需大于等于-1', 'warning');
              return true;
            } else {
              obj.auditLimitFrequency = Number(auditLimitFrequency);
            }
            if (auditLimitNum && !reg.test(auditLimitNum)) {
              message('提示', rowText + '限购数量请填写整数', 'warning');
              return true;
            } else if (auditLimitNum && auditLimitNum < -1) {
              message('提示', rowText + '限购数量需大于等于-1', 'warning');
              return true;
            } else {
              obj.auditLimitNum = Number(auditLimitNum);
            }
            if (auditActivityPriceLimit && !reg.test(auditActivityPriceLimit)) {
              message('提示', rowText + '特价限购请填写整数', 'warning');
              return true;
            } else if (auditActivityPriceLimit && auditActivityPriceLimit < -1) {
              message('提示', rowText + '特价限购需大于等于-1', 'warning');
              return true;
            } else {
              obj.auditActivityPriceLimit = Number(auditActivityPriceLimit);
            }
            list.push(obj);
          });
          if (isNotNext) {
            return;
          }
          message('提示', '文件上传成功', 'success');
          console.log('list', list);
          this.formValue.list = list;
          this.$refs.formRef.validateField('goods');
        } else {
          this.formValue.list = [];
        }
      };
      reader.readAsArrayBuffer(file.raw);
    },
    onError() {
      message('错误', '文件上传失败', 'error');
    },
  },
  mounted() {},
};
